﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Company.Utility;
using Company.Utility.Encrypt;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Mvc;
using static System.IO.Directory;

namespace Company.Project.Web.ImageServices.Controllers
{
    public class FileController : Controller
    {
        // GET: File
        public ActionResult Upload()
        {
            try
            {
                var sign = Request.Form["sign"];
                var name = Request.Form["name"];
                List<string> suffixList = new List<string> { ".RAR", ".ZIP", ".7Z", ".GZ ", ".BZ", ".ACE", ".UHA", ".UDA", ".ZPAQ" };

                if (string.IsNullOrEmpty(sign) || string.IsNullOrEmpty(name))
                {
                    return Content("{\"success\":false,\"filename\":\"\",\"message\":\"签名错误!\"}");
                }
                var key = ReadConfig.ReadAppSetting("ImageUploadKey");
                var date = DateTime.MinValue;
                DateTime.TryParse(Request.Form["date"], out date);
                if ((DateTime.Now - date).TotalMinutes > 5)
                {
                    return Content("{\"success\":false,\"filename\":\"\",\"message\":\"签名授权超时!\"}");
                }
                var md5 = MD5Helper.GetMd5(key + name + date + key);
                if (sign != md5)
                {
                    return Content("{\"success\":false,\"filename\":\"\",\"message\":\"签名错误!\"}");
                }
                var sExtension = Path.GetExtension(name);
                if (!suffixList.Exists(x => x.ToLower() == sExtension?.ToLower()))
                {
                    throw new CustomException("只能上传压缩包,请压缩之后再上传!");
                }
                Response.ContentType = "text/plain";
                var arr = Convert.FromBase64String(Request.Form["UploadFile"]);
                //var ms = new MemoryStream(arr);
                //20mb=1024*1024*20 转换为字节
                if (arr.Length > 20971520)
                {
                    throw new CustomException("文件过大,请重新选择");
                }
                //取出请求参数
                var request = Request;
                var sImgPath = ""; //原路径
                if (!string.IsNullOrEmpty(request.Form["Path"]))
                {
                    //获取客户端传来的Path参数
                    var sPath = request.Form["Path"];
                    sImgPath = $"{Directory.GetCurrentDirectory()}/UserFile/" + sPath + "/" + DateTime.Now.ToString("yyyyMM") + "/";
                }
                var uploadPath = sImgPath;
                if (!Exists(uploadPath))
                {
                    CreateDirectory(uploadPath);
                }
                var sFileName = DateTime.Now.ToString("ddHHmmssfff") + sExtension; //组装文件名
                uploadPath += sFileName;
                FileStream fs = new FileStream(uploadPath, FileMode.Create);   //创建一个文件流
                //将byte数组写入文件中
                fs.Write(arr, 0, arr.Length);
                //所有流类型都要关闭流，否则会出现内存泄露问题          
                fs.Close();
                return Content("{\"success\":true,\"filename\":\"" + "/UserFile/" + request.Form["Path"] + "/" + DateTime.Now.ToString("yyyyMM") + "/" + sFileName + "\"}");
            }
            catch (CustomException e)
            {
                LoggerHelper.Log(e.Message);
                return Content("{\"success\":false,\"filename\":\"" + e.Message + "\"}");
            }
            catch (Exception e)
            {
                LoggerHelper.Log("文件上传异常:" + e.Message + ",详细错误:" + e.GetBaseException().Message);
            }
            return Content("{\"success\":false,\"filename\":\"\"}");
        }
    }
}